package client

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"

	m "gitee.com/chenhonghua/common-service/cmd/segment/model"
	"gitee.com/chenhonghua/ginorigin/env"
	"gitee.com/chenhonghua/ginorigin/log"
)

var (
	_apiUrl = fmt.Sprintf("%s/api/v1/seg", env.StringVal("SERVICE_HOSTPORT_OF_SEGMENT", "http://localhost:58782"))
	_client = &http.Client{}
)

type response struct {
	Code int      `json:"code"`
	Msg  string   `json:"msg"`
	Data []m.Text `json:"data"`
}

func Do(text string, isSearchMod bool) (segs []m.Text, e error) {
	text = strings.TrimSpace(text)
	if len(text) == 0 {
		return nil, fmt.Errorf("text is empty")
	}
	u, e := url.Parse(_apiUrl)
	if e != nil {
		return nil, e
	}
	q := u.Query()
	q.Add("text", text)
	q.Add("is_search_mod", fmt.Sprintf("%v", isSearchMod))
	u.RawQuery = q.Encode()
	req := http.Request{Method: "GET", URL: u}
	resp, e := _client.Do(&req)
	if e != nil {
		return nil, e
	}
	defer resp.Body.Close()
	d, e := io.ReadAll(resp.Body)
	if e != nil {
		return nil, e
	}
	var restfulResp response
	if e := json.Unmarshal(d, &restfulResp); e != nil {
		log.Errorf("json.Unmarshal error: %s", string(d))
		return nil, e
	}
	return restfulResp.Data, nil
}
